import cv2
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# 读入图像
img1 = cv2.imread('afterglow.jpeg', 0)
img2 = img1.copy()

gray_level = add_histogram = np.zeros(256) #存放灰度值个数以及累计直方图

# 统计灰度值（0-255）的个数
for i in range(1080):
    for j in range(1418):
        gray_level[img1[i, j]] += 1

# 灰度直方图
gray_histogram = gray_level / (1080*1418)

# 累计直方图
for u in range(256):
    a = 0
    for v in range(u+1):
        a += gray_histogram[v]
        add_histogram[u] = a

# 取整扩展
for k in range(256):
    add_histogram[k] = int(255*add_histogram[k] + 0.5)

# 确定映射
map = pd.Series(add_histogram, np.arange(256))

# 直方图均衡化
for o in range(1080):
    for p in range(1418):
        if img2[o, p] in map.index:
            img2[o, p] = map[img2[o, p]]

# 显示图像
plt.figure(figsize=(10,4),dpi=120)
plt.subplot(221),plt.imshow(img1, cmap = 'gray')
plt.title('original'),plt.axis('off')
plt.subplot(222),plt.imshow(img2, cmap = 'gray')
plt.title('histogram equalization'), plt.axis('off')

# 直方图显示
plt.subplot(223),plt.hist(img1.ravel(), bins=256)
plt.subplot(224),plt.hist(img2.ravel(), bins=256)
plt.show()